package com.gxa.web.servlet;
import com.alibaba.fastjson.JSONObject;
import com.gxa.common.R;
import com.gxa.service.SysUserService;
import com.gxa.service.impl.SysUserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Servlet作用：
 *    1. 接收前端的请求
 *    2. 作出响应
 *
 * Servlet虽然进企业不会用到它，但是它的底层大家下来一定要去学好，学精。
 *    1. 重点掌握2个接口对象：HttpServletRequest HttpServletResponse
 *    2. 看Servlet底层源码：extends HttpServlet extends GenericServlet implements Servlet, ServletConfig
 *    3. Servlet生命周期：
 *        void init(ServletConfig var1) throws ServletException;
 *        ServletConfig getServletConfig();
 *        void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;
 *        String getServletInfo();
 *        void destroy();
 *    4. 掌握Servlet的设计模式：单例设计模式(8种实现方式)
 *
 */
@WebServlet("/login") //登录接口
public class LoginServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 接收账户
        String account = request.getParameter("account");
        // 接收密码
        String password = request.getParameter("password");
        // 设置响应的类型
        response.setContentType("application/json;charset=utf-8");
        try{
            // 将参数传递给Service层
            SysUserService sysUserService = new SysUserServiceImpl(); //多态
            // 调用方法
            R result = sysUserService.login(account,password);
            response.getWriter().write(JSONObject.toJSONString(result));
        }catch (Exception e){
            e.printStackTrace();
            response.getWriter().write(JSONObject.toJSONString(R.error()));
        }
        // 刷新
        response.getWriter().flush();
        // 关闭流
        response.getWriter().close();
    }

}
